<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 *
 * 权限控制类
 * auther xiaomai
 */
class CheckLang
{
	private $_CI;
	private $node;  //节点


	
	 /**
     * 构造函数
     * @access public
     * @return void
     */
    public function __construct()
    {
        /** 获取CI句柄 */
		$this->_CI = & get_instance();
		$this->_CI->load->database();
		$this->_CI->load->model('mauth');
		$this->getNode();
		$this->CheckLang();
    }
	
    function CheckLang()
	{
		
		if(strpos($this->node, 'login') !== false 
			|| $this->node=='/management/ajaxbutton'
			|| $this->node=='/user/onedit'
			|| $this->node=='/user/edituser'
			|| $this->node=='/user/savepassword'
			|| $this->node=='/oversea/ajaxbutton'
			|| $this->node=='/overseaapi/ajaxbutton'
			|| $this->node=='/datareport/ajaxbutton'
			|| $this->node=='/datareport/index'
			|| $this->node=='/oversea/savedelivery'
			|| $this->node=='/oversea/savecompare'
			|| $this->node=='/oversea/compare'
			|| $this->node=='/oversea/showcompare'
			|| $this->node=='/oversea/cargostatus'
			|| $this->node=='/oversea/editshowplan'
			|| $this->node=='/oversea/showtask'
			|| $this->node=='/oversea/showbox'
			|| $this->node=='/oversea/showplandetail'
			|| $this->node=='/Welcome'
			|| $this->node=='/Welcome/index'
			|| $this->node=='/management/webset'
			|| $this->node=='/index.php'
			|| $this->node=='/login/index'
			|| $this->node=='/login/logincheck'
			|| $this->node=='/product/index'
			|| $this->node=='/product/ajaxbutton'
			|| $this->node=='/order/ajaxbutton'
			|| $this->node=='/order/index'
			|| $this->node=='/doit/sfexpress'
			|| $this->node=='/doit/ajaxbutton'
			|| $this->node=='/factory/ajaxbutton'
			|| $this->node=='/overseaapi/doCrontabUkTask'	//英华英国仓
			|| $this->node=='/overseaapi/doCrontabTask'		//英华德国仓
			|| $this->node=='/overseaapi/doCrontabUsaTask'		//美国仓api
			|| $this->node=='/overseaapi/doCrontabWinitTask'		//美西仓
			|| $this->node=='/user/ajaxbutton'
			|| $this->node=='/batchorder/ajaxbutton'
			|| $this->node=='/batchfactoryorder/ajaxbutton'
			|| $this->node=='/orderlist/editorder'
			|| $this->node=='/orderlist/ajaxbutton'
			|| $this->node=='/order/saveexpresstype'
			|| $this->node=='/order/saveordersearch'
			|| $this->node=='/batchorder/updBatchOrderList'
			|| $this->node=='/exportorder/ajaxbutton'
			|| $this->node=='/deliverorder/ajaxbutton'
			|| $this->node=='/Expressshipment/ajaxbutton'
            || $this->node=='/expressshipment/ajaxbutton'
            || $this->node=='/MoneyRateManage/ajaxbutton'
            || $this->node=='/JpYahooOrder/saveRequestOrder'
            || $this->node=='/CheckExpressPrice/checkDataValidity'
            || $this->node=='/CheckExpressPrice/ajaxbutton'
            || $this->node=='/StoreManage/ajaxbutton'
			|| $this->node=='/report/ajaxbutton'
            || $this->node=='/bonanzaapi/request'
			|| $this->node=='/purchase/ajaxbutton'
			|| $this->node=='/paypal/ajaxbutton'
            || $this->node=='/EbayMessage/ajaxbutton'
			|| $this->node=='/ebayMessage/ajaxbutton'
            || $this->node=='/sales/ajaxbutton'
			|| $this->node=='/productprint/ajaxbutton'
			|| $this->node=='/externalBuy/ajaxbutton'
			|| $this->node=='/applybuy/ajaxbutton'
			|| $this->node=='/JpYahooOrder/getFactory'
			|| $this->node=='/JpYahooOrder/ajaxbutton'
            || $this->node=='/factorydetail/ajaxbutton'
            
            || $this->node=='/taobaoapi/getTaoBaoNewOrders'
			|| $this->node=='/goodsreport/factoryproduct'
			|| $this->node=='/goodsreport/Europeorder'
			|| $this->node=='/goodsreport/Europenvorder'
			|| $this->node=='/goodsreport/Europetongyongorder'
			|| $this->node=='/goodsreport/YzEuropeorder'
			|| $this->node=='/goodsreport/YzEuropenvorder'
			|| $this->node=='/goodsreport/YzEuropetongyongorder'
			|| $this->node=='/EbayMessage/importMsg'
			|| $this->node=='/exportorder_Remote/ajaxbutton'
			|| $this->node=='/Wishproduct/ajaxbutton'
			|| $this->node=='/wishproduct/ajaxbutton'
			|| $this->node=='/orderexcel/ajaxbutton'
			|| $this->node=='/magento/ajaxbutton'
			|| $this->node=='/stocks/ajaxbutton'
			|| $this->node=='/oversea/demandList'
			|| $this->node=='/oversea/deliveryplan'
			|| $this->node=='/welcome/ajaxbutton'
			|| $this->node=='/datareport/externalBuy_refund'
			|| $this->node=='/expressshipment/datalist'
			|| $this->node=='/magento/getallproduct'
			|| $this->node=='/magento/saveupload'





		
		)
		{
			
			//login 相关的页面不进行判断
		}else{


			if(!$_COOKIE["userid"])	//判断是否登录
			{
				header("location:/login");
				//show_error('请先登录！<a href="/login">点击登录</a>');
			}
			$data = $this->check($_COOKIE["userid"]);
			if(!$data['rt']){
							

				echo "<div style='color:red;'>	<b>功能：{$this->node}</B><br>对不起，您没有权限执行此操作!<br>如果你要开通这个权限。请先联系管理员。然后再<a href=/login/>重新登录</a></div>";
				die;
			}
			else{
				//var_dump($data);
			}
			
		}
	}
	//获取url节点
	protected function getNode(){
		//$CONTROLLER_NAME =  $this->_CI->router->fetch_class();
		//$ACTION_NAME =  $this->_CI->router->fetch_method();    // 当前使用方法
		//$this->node = strtolower($CONTROLLER_NAME.'/'.$ACTION_NAME);
			$file=str_replace("/index.php","",$_SERVER['PHP_SELF']);
		 	$reg="/\/\d+/is";
			$file= preg_replace($reg,"",$file);
			if(substr($file,strlen($file)-1,1)=="/"){
				$file=substr($file,0,strlen($file)-1);
			}
			$this->node = $file;
	}
	public function check($uid, $type=1, $mode='url', $relation='or') {
			$authdata	  = $this->getAuthList($uid,$type); //获取用户需要验证的所有有效规则列表
			$authList	  = $authdata["authList"];
			$authListname = $authdata["authListname"];
			if(!$authdata)
			{
				return array("name"=>'未设置任何权限',"rt"=>false);
			}
			if($authdata==9999)
			{
				return array("name"=>'超级管理员',"rt"=>true);
			}
			
			$name = $this->node;   //这里可以根据分组做

			//这一步理论上可以省了（参考TP的）
			if (is_string($name)) {
				$name = strtolower($name);
				if (strpos($name, ',') !== false) {
					$name = explode(',', $name);
				} else {
					$name = array($name);
				}
			}
			
		
			$list = array(); //保存验证通过的规则名
			if ($mode=='url') {
				$REQUEST = unserialize( strtolower(serialize($_REQUEST)) );
			}
			
		
		
			foreach ( $authList as $key=>$auth ) {
				$query = preg_replace('/^.+\?/U','',$auth);
				
		
				if ($mode=='url' && $query!=$auth ) {
					parse_str($query,$param); //解析规则中的param
					$intersect = array_intersect_assoc($REQUEST,$param);
					$auth = preg_replace('/\?.*$/U','',$auth);
					if ( in_array($auth,$name) && $intersect==$param ) {  //如果节点相符且url参数满足
						$list[] = $auth ;
					}
					
				}else if (in_array($auth , $name)){
					
					$list[] = $auth ;
					$authname = $authListname[$key];
					
				}else{
					$authname = $authListname[$key];
				}
			}

				
			

			if ($relation == 'or' and !empty($list)) {
				//return true;
				return array("name"=>$authname,"rt"=>true);
			}

			$diff = array_diff($name, $list);	//比较两个数组的键值，并返回差集：
			if ($relation == 'and' and empty($diff)) {
				//return true;
				return array("name"=>$authname,"rt"=>true);
			}
			return array("name"=>$authname,"rt"=>false);
    }


	/**
     * 获得权限列表
     * @param integer $uid  用户id
     * @param integer $type 
	 * Array ( [0] => admin/index/index [1] => admin/index/test [2] => admin/user/index [3] => admin/game/index [4] => admin/game/game_list [5] => admin/game/game_add )
	 * protected
     */
     protected function getAuthList($uid,$type=1) {  //应该通过groupid好点
		static $_authList = array(); //保存用户验证通过的权限列表
		
        $rsdb = $this->_CI->db->get_one("SELECT * FROM d_user WHERE id='".$uid."'");
		
	

		/*
		if($rsdb["power"]=="")	//如果自身没有权限，继承用户组权限
		{
			
			$group = $this->_CI->db->get_where('d_group',"id='".$rsdb["department"]."'")->result_array();
			
			if($group[0]["rules"])
			{
				$power = $group[0]["rules"];
			}else{
				$power = "";
			}
			if($power)
			{
				$rsdb["power"] = $power;
			}else{
				return false;
			}
		}*/
		if($rsdb["power"]=="all")	//所有权限
		{
			return 9999;
		}else{
			//合并自身权限和用户组的权限
			$group = $this->_CI->db->get_where('d_group',"id='".$rsdb["department"]."'")->result_array();
			if($rsdb["power"] && $group[0]["rules"])
			{
				$newpower = $rsdb["power"].",".$group[0]["rules"];
			}elseif($rsdb["power"] &&  $group[0]["rules"]=='' )
			{
				$newpower = $rsdb["power"];
			}elseif($rsdb["power"] =='' &&  $group[0]["rules"])
			{
				$newpower = $group[0]["rules"];
			}else{
				$newpower = "";
			}

			if($newpower)
			{
				//去空，去重量
				$powerstr = array_unique(array_filter(explode(",",$newpower)));
				$newpower = implode(",",$powerstr);
				$rsdb["power"] = $newpower;
			}else{
				return false;
			}

			//print_r($group[0]["rules"]);
			
		
		}
		$ids = explode(',', trim($rsdb['power']));
		
		$this->_CI->db->select('*');
		$this->_CI->db->where_in('id',$ids);
		$query = $this->_CI->db->get('d_menu');	
		$rules=$query->result_array();
		
		
		//循环规则，判断结果。
        $authList = array();   //
        foreach ($rules as $rule) {
            if (!empty($rule['value_fied'])) { //根据value_txt进行验证
					
					

					if(strpos($rule['value_fied'], '/') !== false)
					{
						$authList[] = strtolower($rule['value_fied']);
						$authListname[] = strtolower($rule['value_txt']);
					}
                    
               
				
            } else {
                //只要存在就记录
                $authList[] = strtolower($rule['value_fied']);
            }
        }
		//只要存在就记录
        $authList[] = strtolower($rule['value_fied']);
		
		
		//这一步，为了提高性能，可以用缓存服务这里暂时不用
		//return array_unique($authList);
		return array("authList"=>array_unique($authList),"authListname"=>array_unique($authListname));

    }
}